package Playlist
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.filesystem.File;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.xml.XMLDocument;
	import flash.xml.XMLNode;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import org.osmf.events.PlayEvent;
	
	public class XmlPlaylist extends EventDispatcher
	{
		private var playlists:ArrayCollection = new ArrayCollection();
		
		public function XmlPlaylist()
		{
		}
		
		public function getPlaylists() : ArrayCollection
		{
			return playlists;
		}
		
		//***********************************
		//******* LOADING *******************
		//***********************************
		public function loadFromFile(path:String) : void
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onLoadingComplete);
			var f:File = new File(path);
			if (f.exists)
			{
				var request:URLRequest = new URLRequest(f.url);
				loader.load(request);
			}
		}
		protected function onLoadingComplete(event:Event) : void
		{
			var load:URLLoader = URLLoader(event.target);
			var node:XML = XML(load.data);
			if (node.localName() == "playlists")
			{
				parsePlaylist(node);
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}
		protected function parsePlaylist(node:XML) : void
		{
			var children:XMLList = node.children();
			var child:XML;
			for each  (child in children)
			{
				if (child.localName() == "playlist")
				{
					var playlist:Playlist = new Playlist();
					parseMusic(child, playlist);
					playlists.addItem(playlist);
				}
			}
		}
		protected function parseMusic(node:XML, playlist:Playlist) : void
		{
			var children:XMLList = node.children();
			var child:XML;
			for each  (child in children)
			{
				if (child.localName() == "music")
				{
					playlist.AddSong(child);
				}
			}
		}
		//***********************************
		//********* SAVING ******************
		//***********************************
		public function saveIntoFile(playlists:ArrayCollection, path:String) : void
		{
			var xml:XML = new XML(<playlists></playlists>);
			
			for each (var playlist:Playlist in playlists)
			{
				var node_pl:XML = new XML(<playlist></playlist>);
				for (var i:int = 0; i < playlist.length(); ++i)
				{
					var music:String = playlist.getsongName(i);
					var node_m:XML = new XML(<music></music>);
					node_m.appendChild(music);
					node_pl.appendChild(node_m);
				}
				xml.appendChild(node_pl);
			}
			var data:ByteArray = new ByteArray();
			data.writeUTFBytes(xml);
			new File(path).save(data);
			
			
		}
	}
}